import './index.scss'

import React, { FunctionComponent, useCallback, useEffect, useRef, useState } from 'react'
import { View } from '@tarojs/components'

import models, { WrapModel } from '@/models'
import { goToPage, handleUserRouterError, message } from '@/utils'

import { LoginContentDrawer } from './components/content-drawer'

export type IFloatWrapperBaseProps = {
  /** 标题 */
  title?: React.ReactNode;
};

export type IFloatWrapperOpenProps<P = {}> = IFloatWrapperBaseProps & {
  /** 内容属性 */
  props?: P;
};

export type IFloatWrapperRef<P = {}> = {
  /** 浮层弹窗打开接口 */
  open: (openProps?: IFloatWrapperOpenProps<P>) => void;
  /** 浮层弹窗关闭接口 */
  close: () => void;
};


const baseCls = 'login-page';

const Login: FunctionComponent<{}> = () => {
  const [loading, setLoading] = useState(false);

  const agreementRef = useRef<IFloatWrapperRef>(null);

  const afterLogin = useCallback(() => {
    message.success('登录成功', 1500).then(() => {
      goToPage('/pages/index/index', {
        method: 'reLaunch',
      });
    });
  }, []);

  const handleLogin = useCallback(async () => {
    setLoading(true);

    const hide = message.loading('登录中');

    try {
      await models.user.login();
      hide();

      afterLogin();
    } catch (err) {
      hide();

      handleUserRouterError(err);
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    const fn = async () => {
      if (models.user.canAutoLogin) {
        setLoading(true);

        const hide = message.loading('自动登录中');

        try {
          await models.user.autoLogin();
          hide();

          afterLogin();
        } catch (err) {
          hide();
          handleUserRouterError(err);
        } finally {
          setLoading(false);
        }
      } else {
        agreementRef.current?.open();
      }
    };

    fn();
  }, []);
  return (
    <View className={baseCls}>
      <LoginContentDrawer
        ref={agreementRef}
        logo="蓝信封"
        maskClosable
        okText="同意"
        showOkBtn
        onOk={() => {
          handleLogin();
        }}
        cancelText="不同意"
        showCancelBtn
        hideTitle
      />
    </View>
  );
};

export default WrapModel(Login);